// pages/auction/auction.ts
import { auctionAPI } from '../../utils/api';

interface AuctionItem {
  id: number;
  title: string;
  description: string;
  category: string;
  starting_price: string;
  current_price: string;
  buyout_price: string | null;
  status: 'active' | 'pending' | 'completed';
  seller_id: number;
  seller_nickname: string;
  winner_id: number | null;
  winner_nickname: string | null;
  image_url: string | null;
  view_count: number;
  bid_count: number;
  created_at: string;
  updated_at: string;
}

interface ApiResponse {
  items: AuctionItem[];
  total: number;
  page: number;
  size: number;
  has_next: boolean;
  has_prev: boolean;
}

// 工具函数：确保数据唯一性
function ensureUniqueItems(items: AuctionItem[]): AuctionItem[] {
  const seen = new Set();
  return items.filter(item => {
    if (seen.has(item.id)) {
      return false;
    }
    seen.add(item.id);
    return true;
  });
}

Page({
  data: {
    auctionItems: [] as AuctionItem[],
    allItems: [] as AuctionItem[], // 保存所有原始数据
    loading: false,
    hasMore: true,
    currentPage: 0,
    pageSize: 10,
    searchKeyword: '',
    totalItems: 0,
    currentCategory: 'all',
    currentStatus: 'all', // 当前拍卖状态
    activeItems: 0,
    todayBids: 0,
    globalLoading: false,
    currentScene: '', // 当前scene参数
    searchParams: { // 搜索参数
      category: 'all',
      keyword: '',
      status: 'all'
    },
    // 弹框相关数据
    showItemModal: false,
    modalTitle: '',
    modalContent: ''
  },

  onLoad(options: any) {
    console.log('拍卖页面加载', options);
    
    // 从全局数据获取scene参数
    const app = getApp<IAppOption>();
    const scene = app.globalData.currentScene;
    this.setData({ currentScene: scene });
    
    // 直接加载拍卖商品列表
    this.loadAuctionItems();
  },

  onShow() {
    // 页面显示时刷新数据，保持当前搜索条件
    this.refreshData();
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  onReachBottom() {
    console.log('触发滚动到底部事件', {
      hasMore: this.data.hasMore,
      loading: this.data.loading,
      currentPage: this.data.currentPage,
      totalItems: this.data.totalItems,
      currentItems: this.data.auctionItems.length,
      allItemsCount: this.data.allItems.length,
      searchParams: this.data.searchParams
    });
    
    // 检查是否有更多数据可以加载
    const canLoadMore = this.data.hasMore && !this.data.loading;
    
    if (canLoadMore) {
      console.log('开始加载更多数据');
      this.loadMore();
    } else {
      console.log('跳过加载更多:', {
        hasMore: this.data.hasMore,
        loading: this.data.loading,
        reason: this.data.loading ? '正在加载中' : '没有更多数据'
      });
      
      // 如果hasMore为false但用户滚动到底部，可能是状态错误，尝试强制重置
      if (!this.data.hasMore && !this.data.loading && this.data.totalItems > this.data.allItems.length) {
        console.log('检测到可能的hasMore状态错误，尝试强制重置');
        this.setData({ hasMore: true });
        setTimeout(() => {
          this.loadMore();
        }, 100);
      }
    }
  },

  // 加载拍卖商品列表
  async loadAuctionItems(refresh: boolean = false) {
    if (this.data.loading) {
      console.log('正在加载中，跳过重复请求');
      return;
    }

    try {
      this.setData({ loading: true });

      // 使用真实API，传递搜索参数
      const skip = refresh ? 0 : this.data.currentPage * this.data.pageSize;
      const { searchParams } = this.data;
      
      console.log('开始加载商品', {
        refresh,
        skip,
        pageSize: this.data.pageSize,
        currentPage: this.data.currentPage,
        searchParams,
        calculatedSkip: skip
      });
      
      const response: ApiResponse = await auctionAPI.getAuctionItems(
        skip, 
        this.data.pageSize,
        searchParams.category,
        searchParams.keyword,
        searchParams.status
      );
      
      // 调试：打印API返回的数据结构和搜索参数
      console.log('API返回数据:', response);
      console.log('返回商品数量:', response.items.length || 0);
      console.log('has_next:', response.has_next);
      console.log('total:', response.total);
      
      if (response.items && response.items.length > 0) {
        console.log('第一个商品的分类:', response.items[0].category);
        console.log('所有商品的分类:', response.items.map(item => ({ id: item.id, category: item.category, title: item.title })));
      }
      
      if (refresh) {
        const uniqueItems = ensureUniqueItems(response.items);
        this.setData({
          auctionItems: uniqueItems,
          allItems: uniqueItems, // 保存原始数据
          currentPage: 1, // 刷新后设置为第1页，因为已经加载了第一页数据
          totalItems: response.total,
          hasMore: response.has_next
        });
        console.log('刷新完成，页码设置为1，hasMore:', response.has_next);
      } else {
        // 合并数据并确保唯一性
        const combinedItems = [...this.data.allItems, ...response.items];
        const uniqueItems = ensureUniqueItems(combinedItems);
        const newPage = this.data.currentPage + 1;
        
        this.setData({
          auctionItems: uniqueItems,
          allItems: uniqueItems, // 保存原始数据
          currentPage: newPage,
          totalItems: response.total,
          hasMore: response.has_next
        });
        console.log('加载更多完成，页码更新为:', newPage, 'hasMore:', response.has_next);
      }

      // 处理图片加载错误
      this.handleImageErrors();
      
      // 更新统计数据
      this.updateStats();
      
      // 额外检查：如果当前加载的商品数量等于或超过总数，则设置hasMore为false
      if (response.items && response.items.length > 0) {
        // 使用allItems的长度来计算已加载的商品数量，因为auctionItems可能被过滤过
        const totalLoaded = this.data.allItems.length;
        console.log('已加载商品数量检查:', {
          totalLoaded,
          total: response.total,
          hasMore: response.has_next,
          currentPage: this.data.currentPage
        });
        
        if (totalLoaded >= response.total) {
          console.log('已加载所有商品，设置hasMore为false');
          this.setData({ hasMore: false });
        } else if (response.has_next && !this.data.hasMore) {
          // 如果API返回has_next为true但当前hasMore为false，强制更新
          console.log('API返回has_next为true，强制更新hasMore状态');
          this.setData({ hasMore: true });
        }
      }

    } catch (error) {
      console.error('加载拍卖商品失败:', error);
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'error'
      });
      // 确保在错误时也重置loading状态
      this.setData({ loading: false });
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
      console.log('加载完成，loading状态已重置');
    }
  },

  // 刷新数据
  refreshData() {
    console.log('刷新数据，当前状态:', {
      currentPage: this.data.currentPage,
      hasMore: this.data.hasMore,
      totalItems: this.data.totalItems,
      currentItems: this.data.auctionItems.length
    });
    this.loadAuctionItems(true);
  },

  // 加载更多
  loadMore() {
    console.log('手动触发加载更多', {
      currentPage: this.data.currentPage,
      hasMore: this.data.hasMore,
      loading: this.data.loading,
      totalItems: this.data.totalItems,
      currentItems: this.data.auctionItems.length
    });
    
    // 如果当前没有更多数据但用户手动点击，强制重置状态
    if (!this.data.hasMore) {
      console.log('强制重置hasMore状态');
      this.setData({ hasMore: true });
    }
    
    this.loadAuctionItems(false);
  },

  // 搜索输入
  onSearchInput(e: any) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认
  onSearchConfirm() {
    this.performSearch();
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    
    // 更新搜索参数
    const searchParams = {
      ...this.data.searchParams,
      keyword: ''
    };
    
    this.setData({ searchParams: searchParams });
    
    // 重新调用接口
    this.refreshData();
  },

  // 执行搜索
  performSearch() {
    const keyword = this.data.searchKeyword.trim();
    
    // 更新搜索参数
    const searchParams = {
      ...this.data.searchParams,
      keyword: keyword
    };
    
    this.setData({ 
      searchParams: searchParams,
      currentPage: 0, // 重置页码
      hasMore: true,  // 重置hasMore状态
      auctionItems: [], // 清空当前商品列表
      allItems: []      // 清空所有商品数据
    });
    
    console.log('执行搜索，重置分页状态和商品数据');
    
    // 重新调用接口
    this.refreshData();
  },

  // 处理图片加载错误
  handleImageErrors() {
    // 为没有图片的商品设置默认图片
    const items = this.data.auctionItems.map(item => ({
      ...item,
      image_url: item.image_url || '/static/warrior-01.png'
    }));
    this.setData({ auctionItems: ensureUniqueItems(items) });
  },

  // 图片加载错误
  onImageError(e: any) {
    const index = e.currentTarget.dataset.index;
    const items = [...this.data.auctionItems];
    items[index].image_url = '/static/warrior-01.png';
    this.setData({ auctionItems: ensureUniqueItems(items) });
  },

  // 点击商品卡片
  onItemTap(e: any) {
    const item = e.currentTarget.dataset.item;
    console.log('点击商品:', item);
    
    // 构建商品详情内容
    const detailContent = this.buildItemDetailContent(item);
    
    // 显示商品详情弹框
    this.setData({
      showItemModal: true,
      modalTitle: item.title,
      modalContent: detailContent
    });
  },

  // 构建商品详情内容
  buildItemDetailContent(item: AuctionItem) {
    return `
      <div class="item-detail-simple">
        <div class="item-description-content">
          <p>${item.description || '暂无商品描述'}</p>
        </div>
      </div>
    `;
  },

  // 获取状态文本
  getStatusText(status: string): string {
    switch (status) {
      case 'active':
        return '🔥 进行中';
      case 'pending':
        return '⏰ 等待中';
      case 'completed':
        return '✅ 已结束';
      default:
        return '未知状态';
    }
  },

  // 点击操作按钮
  onActionTap(e: any) {
    const item = e.currentTarget.dataset.item;
    const action = e.currentTarget.dataset.action;

    if (action === 'bid') {
      this.handleBid(item);
    } else if (action === 'wait') {
      this.handleWait(item);
    }
  },

  // 处理竞价
  handleBid(item: AuctionItem) {
    wx.showModal({
      title: '参与竞价',
      content: `确定要参与"${item.title}"的竞价吗？当前价格：${item.current_price} MB`,
      confirmText: '确定竞价',
      cancelText: '取消',
      success: async (res) => {
        if (res.confirm) {
          await this.placeBid(item);
        }
      }
    });
  },

  // 处理等待拍卖
  handleWait(item: AuctionItem) {
    wx.showToast({
      title: '商品等待拍卖中',
      icon: 'none'
    });
  },

  // 提交竞价
  async placeBid(item: AuctionItem) {
    try {
      wx.showLoading({ title: '提交竞价中...' });
      
      // 这里可以添加竞价金额输入逻辑
      const bidAmount = parseFloat(item.current_price) + 1; // 示例：加价1MB
      
      await auctionAPI.placeBid(item.id, bidAmount);
      
      wx.hideLoading();
      wx.showToast({
        title: '竞价成功',
        icon: 'success'
      });
      
      // 刷新数据
      this.refreshData();
      
    } catch (error) {
      wx.hideLoading();
      console.error('竞价失败:', error);
      wx.showToast({
        title: '竞价失败，请重试',
        icon: 'error'
      });
    }
  },

  // 设置分类
  setCategory(e: any) {
    const category = e.currentTarget.dataset.category;
    console.log('切换分类:', category);
    
    // 更新搜索参数
    const searchParams = {
      ...this.data.searchParams,
      category: category
    };
    
    this.setData({ 
      currentCategory: category,
      searchParams: searchParams,
      currentPage: 0, // 重置页码
      hasMore: true,  // 重置hasMore状态
      auctionItems: [], // 清空当前商品列表
      allItems: []      // 清空所有商品数据
    });
    
    console.log('切换分类，重置分页状态和商品数据');
    
    // 重新调用接口
    this.refreshData();
  },

  // 设置拍卖状态
  setStatus(e: any) {
    const status = e.currentTarget.dataset.status;
    console.log('切换状态:', status);
    
    // 更新搜索参数
    const searchParams = {
      ...this.data.searchParams,
      status: status
    };
    
    this.setData({ 
      currentStatus: status,
      searchParams: searchParams,
      currentPage: 0, // 重置页码
      hasMore: true,  // 重置hasMore状态
      auctionItems: [], // 清空当前商品列表
      allItems: []      // 清空所有商品数据
    });
    
    console.log('切换状态，重置分页状态和商品数据');
    
    // 重新调用接口
    this.refreshData();
  },

  // 过滤商品（保留用于兼容性，但主要使用服务端过滤）
  filterItems() {
    const { currentCategory, allItems } = this.data;
    console.log('过滤分类:', currentCategory, '总数据量:', allItems.length);
    
    if (currentCategory === 'all') {
      // 显示所有商品
      this.setData({ 
        auctionItems: allItems
        // 注意：不设置 totalItems，保持API返回的正确总数
      });
    } else {
      // 根据分类过滤
      const filteredItems = allItems.filter(item => item.category === currentCategory);
      console.log('过滤后数量:', filteredItems.length);
      
      this.setData({ 
        auctionItems: filteredItems
        // 注意：不设置 totalItems，保持API返回的正确总数
      });
    }
    
    // 更新统计数据
    this.updateStats();
  },

  // 重置搜索条件
  resetSearch() {
    const searchParams = {
      category: 'all',
      keyword: '',
      status: 'all'
    };
    
    this.setData({
      currentCategory: 'all',
      currentStatus: 'all',
      searchKeyword: '',
      searchParams: searchParams,
      currentPage: 0, // 重置页码
      hasMore: true,  // 重置hasMore状态
      auctionItems: [], // 清空当前商品列表
      allItems: []      // 清空所有商品数据
    });
    
    console.log('重置搜索条件，清空所有数据');
    
    // 重新调用接口
    this.refreshData();
    
    wx.showToast({
      title: '已重置筛选条件',
      icon: 'success'
    });
  },

  // 刷新
  onRefresh() {
    this.refreshData();
    wx.showToast({
      title: '刷新成功',
      icon: 'success'
    });
  },

  // 筛选
  onFilter() {
    wx.showToast({
      title: '筛选功能开发中',
      icon: 'none'
    });
  },

  // 快速竞价
  onQuickBid() {
    wx.showToast({
      title: '快速竞价功能开发中',
      icon: 'none'
    });
  },

  // 更新统计数据
  updateStats() {
    const activeItems = this.data.auctionItems.filter(item => item.status === 'active').length;
    const todayBids = this.data.auctionItems.reduce((sum, item) => sum + item.bid_count, 0);
    
    // 注意：totalItems 已经在 loadAuctionItems 中通过 response.total 正确设置
    // 这里只更新其他统计数据，不覆盖 totalItems
    this.setData({
      activeItems,
      todayBids
    });
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '好物剪影 - 发现精彩拍卖商品',
      path: '/pages/auction/auction'
    };
  },

  // 关闭弹框
  onModalClose() {
    this.setData({
      showItemModal: false,
      modalTitle: '',
      modalContent: ''
    });
  }

});